package com.zx.centers.socketservice.user;

import io.netty.channel.ChannelHandlerContext;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class OnlineUser {
    //用户表
    private Map<String, ChannelHandlerContext> userToChannel = new ConcurrentHashMap<>();

    private Map<ChannelHandlerContext,String> channelToUser = new ConcurrentHashMap<>();

    public void put(String uid, ChannelHandlerContext uchc){
        channelToUser.put(uchc,uid);
        userToChannel.put(uid, uchc);
    }

    public void remove(String uid){
        if(uid == null){
            return;
        }
        ChannelHandlerContext channelHandlerContext = userToChannel.get(uid);
        if(channelHandlerContext!=null){
            channelToUser.remove(channelHandlerContext);
        }
        userToChannel.remove(uid);
    }

    public void remove(ChannelHandlerContext channelHandlerContext){
        if(channelHandlerContext == null){
            return;
        }
        String uid = channelToUser.get(channelHandlerContext);
        if(uid!=null){
            userToChannel.remove(uid);
        }
        channelToUser.remove(channelHandlerContext);
    }

    public ChannelHandlerContext get(String uid){
        return userToChannel.get(uid);
    }

    public String get(ChannelHandlerContext channelHandlerContext){
        return channelToUser.get(channelHandlerContext);
    }
}
